import React from 'react';
import { Card, notification } from 'antd';
import styles from './home.less';
import { useEffect, useRef, useState } from 'react';
import { useNavigate, Routes, Route, useLocation } from 'react-router-dom';
import request from '@/utils/request'
import * as echarts from 'echarts'
import targetLogo from '@/assets/targetLogo.png';
import resultLogo from '@/assets/result.jpg';
import PublicUtils from "@/utils/publicUtils";

const Home = () => {
  const navigate = useNavigate();
  const [targetData, setTargetData] = useState()
  const [interviewResults, setInterviewResults] = useState()
  const chartRef1 = useRef(null);
  const chartRef2 = useRef(null);
  const [menuPermissions, setMenuPermissions] = useState([]);

  useEffect(() => {
    const cachedPermissions = JSON.parse(localStorage.getItem('authorized'));
    if (cachedPermissions) {
      setMenuPermissions(cachedPermissions);
    }
    getChartData();
    getDeliveryTarget();
    getInterviewResults();
    PublicUtils.dataDictionary();
  }, []);


  //设置为null的值为0
  const setNullToZero = (obj) => {
    if (obj === null) {
      return 0;
    } else if (typeof obj === 'object' && obj !== null) {
      for (let key in obj) {
        obj[key] = setNullToZero(obj[key]);
      }
    }
    return obj;
  }

  //获取目标数据
  const getDeliveryTarget = () => {
    request.get('/dashboard/getDeliveryTarget').then(res => {
      if (res && res.error_code === 200) {
        if (res.data && Object.keys(res.data).length > 0) {
          let processedData = setNullToZero(res.data);
          setTargetData(processedData)
        } else {
          notification.warn({
            message: '数据为空'
          })
        }
      } 
      else {
        notification.error({
          message: res ? res.error_msg : '请求错误'
        })
      }
    })
  }

  //获取面试结果数据
  const getInterviewResults = () => {
    request.get('/dashboard/getInterviewResults').then(res => {
      if (res && res.error_code === 200) {
        if (res.data && Object.keys(res.data).length > 0) {
          let processedData = setNullToZero(res.data);
          setInterviewResults(processedData)
        } else {
          notification.warn({
            message: '数据为空'
          })
        }
        
      } else {
        notification.error({
          message: res ? res.error_msg : '请求错误'
        })
      }
    })
  }

  //获取交付数据、招聘数据
  const [chartData, setChartData] = useState({})
  const getChartData = () => {
    request.get('/dashboard/getChartData', { params: { type: 1 } }).then(res => {
      if (res && res.error_code === 200) {
        let currentData = res.data
        if (currentData.deliveryData.seriesData) {
          currentData.deliveryData.seriesData.forEach((item) => {
            item.type = 'line'
            item.stack = 'Total'
          })
        }
        if (currentData.recruitmentData.seriesData) {
          currentData.recruitmentData.seriesData.forEach((item) => {
            item.type = "bar"
          })
        }
        setChartData(currentData)

      } else {
        notification.error({
          message: res ? res.error_msg : '请求错误'
        })
      }
    })
  }

  //绘制交付数据
  const getDeliveryChar = () => {
    if (chartData?.deliveryData) {
      const chartDom1 = chartRef1.current;//使用useRef获取节点
      if (chartDom1) {
        const myChart1 = echarts.init(chartDom1);
        const option1 = {
          tooltip: {
            trigger: 'axis'
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: chartData.deliveryData.date
          },
          yAxis: {
            type: 'value'
          },
          series: chartData.deliveryData.seriesData,
          legend: {
            bottom: 0,
            left: 'center',
            data: chartData.deliveryData.legendData
          },
        };
        option1 && myChart1.setOption(option1);
      }
    }
  }

  //绘制招聘数据
  const getRecruitmentChar = () => {
    if (chartData?.recruitmentData) {
      const chartDom2 = chartRef2.current;//使用useRef获取节点
      if (chartDom2) {
        const myChart2 = echarts.init(chartDom2);
        const option2 = {
          tooltip: {
            trigger: 'axis',
          },
          legend: {
            bottom: 0,
            left: 'center',
            data: chartData.recruitmentData.legendData
          },

          xAxis: [
            {
              type: 'category',
              data: chartData.recruitmentData.date
            }
          ],
          yAxis: [
            {
              type: 'value'
            }
          ],
          series: chartData.recruitmentData.seriesData
        };
        option2 && myChart2.setOption(option2);
      }
    }
  }


  useEffect(() => {
    getDeliveryChar()
    getRecruitmentChar()

  }, [chartData])

  //展开权限数据函数
  const flattenTree = (tree) => {
    let flattenedArray = [];
    const traverseTree = (node) => {
      flattenedArray.push(node);
      if (node.children && node.children.length > 0) {
        node.children.forEach(child => {
          traverseTree(child);
        });
      }
    };
    tree.forEach(node => {
      traverseTree(node);
    });
    return flattenedArray;
  };

  //跳转到交付计划页面
  const ondeliveryPlan = () => {
    const flattenedData = flattenTree(menuPermissions);
    const permission = flattenedData.find((perm) => perm.path === '/business/deliveryPlan');
    if(permission){
      navigate('/business/deliveryPlan')
    }else{
      notification.error({
        message: '暂无权限'
      })
    }
  }

  //跳转到面试结果页面
  const onResult = () => {
    const flattenedData = flattenTree(menuPermissions);
    const permission = flattenedData.find((perm) => perm.path === '/recruit/interviewResultMobile');
    if(permission){
      navigate('/recruit/interviewResultMobile')
    }else{
      notification.error({
        message: '暂无权限'
      })
    }
  }

  return (
    <div className={styles.contions}>
      <div className={styles.cardItem}>
        <Card
          bordered={true}
          title={<span style={{ color: '#409EFF', borderWidth: '2px' }}>捷径</span>}>
          {(
            <div className={styles.top}>
              <div className={styles.topCard} onClick={ondeliveryPlan}>
                <div style={{ width: "100%", marginTop: "15px", marginLeft: "35px" }}>
                  <span style={{ fontSize: "16px", display: 'block' }}>我的交付目标</span>
                  <span style={{ fontSize: "12px", display: 'block', marginTop: "5px" }}>本月交付目标{targetData?.target} 已完成{targetData?.completion}</span>
                </div>
                <div style={{ marginTop: "10px", marginRight: "25px" }}>
                  <img src={targetLogo} alt="targetLogo" style={{ width: "60px", height: "50px" }}></img>
                </div>
              </div>
              <div className={styles.topCard} onClick={onResult}>
                <div style={{ width: "100%", marginTop: "15px", marginLeft: "35px" }}>
                  <span style={{ fontSize: "16px", display: 'block' }}>跟进面试结果</span>
                  <span style={{ fontSize: "12px", display: 'block', marginTop: "5px" }}>本月待入职{interviewResults?.pendingEmployment} 已入职{interviewResults?.alreadyEmployed} 入职失败{interviewResults?.employmentFailure}</span>
                </div>
                <div style={{ marginTop: "10px", marginRight: "25px" }}>
                  <img src={resultLogo} alt="targetLogo" style={{ width: "60px", height: "50px" }}></img>
                </div>
              </div>
            </div>
          )}
        </Card>
      </div>
      <div className={styles.cardItem}>
        <Card
          bordered={true}
          styles={{ body: { height: '400px', paddingTop: '0px', border: '2px solid #e8e8e8' } }}
          headStyle={{ border: '2px solid #e8e8e8', borderRadius: '0px' }}
          title={<span style={{ color: '#409EFF' }}>交付数据</span>}>
          {
            <div id='deliveryData' ref={chartRef1} style={{ width: '100%', height: '100%' }}></div>
          }
        </Card>
      </div>
      <div className={styles.cardItem}>
        <Card
          bordered={true}
          styles={{ body: { height: '400px', paddingTop: '0px', border: '2px solid #e8e8e8' } }}
          headStyle={{ border: '2px solid #e8e8e8', borderRadius: '0px' }}
          title={<span style={{ color: '#409EFF' }}>招聘数据</span>}>
          {
            <div id='recruitmentData' ref={chartRef2} style={{ width: '100%', height: '100%' }}></div>
          }
        </Card>
      </div>
    </div>
  );
};

export default Home;
